#!/usr/bin/env python
# coding: utf-8

from rediscluster import client
import demjson
import random
import chardet

#此运行在python2 上面，编码方面不太一样
#增加按城市号码池方法
###


class RedisClusterClient(object):
    instance = None
    city_show_num_pool_index_prix = "copShowNumIndex:"
    city_show_num_pool_list_prix = "copShowNumList:"

    def __init__(self, conn_list):
        self.conn_list = conn_list
        RedisClusterClient.instance = self.connect()

    def connect(self):
        """
        init connection
        :return: object
        """
        try:
            # 非密码连接redis集群
            # redisconn = StrictRedisCluster(startup_nodes=self.conn_list)
            # 使用密码连接redis集群
            redisconn = client.RedisCluster(startup_nodes=self.conn_list)
            return redisconn
        except Exception as e:
            print(e)
            return False

    def get_state(self):
        """
        :return:
        """
        res = RedisClusterClient(self.conn_list).connect()
        if not res:
            return False

        dic = res.cluster_info()

        for i in dic:
            ip = i.split(":")[0]
            if dic[i].get('cluster_state'):
                print("status, ip: ", ip, "value: ", dic[i].get('cluster_state'))

    def get_cop_show_num_dict(self, user_id):
        if user_id is None:
            return None
        key = "copShowNumMap:%s" % user_id
        return RedisClusterClient.instance.hgetall(name=key)

    def get_cop_num(self, user_id, city=None):

        b_show_num_dict = self.get_cop_show_num_dict(user_id)
        if b_show_num_dict is None:
            return None
        if city is None:
            """
            direct random one from own show number,if without city param
            """
            if len(b_show_num_dict) > 0:
                rl = list(b_show_num_dict.keys())
                return random.choice(rl)
        else:
            """
            random one from own show number,in a city showNum list
            """
            show_num_list = [x for x, y in b_show_num_dict.items() if y is city]
            if len(show_num_list) > 0:
                return random.choice(show_num_list)

        return None

    def get_cop_num_in_pool(self,city):
        """Take turns getting a display number in a city's number pool"""
        index_key = RedisClusterClient.city_show_num_pool_index_prix + city
        list_key = RedisClusterClient.city_show_num_pool_list_prix + city
        pool_size = RedisClusterClient.instance.llen(list_key)
        if pool_size is None or pool_size == 0:
            return None

        current_index = RedisClusterClient.instance.incr(index_key)

        if current_index >= pool_size:
            RedisClusterClient.instance.delete(index_key)

        show_num = RedisClusterClient.instance.lindex(list_key, current_index)
        if show_num is not None:
            return show_num

        return None

    def get_last_call_info(self, key):
        b_last_call_info_dict = RedisClusterClient.instance.hgetall(key)
        return b_last_call_info_dict


nodes = [
    {'host': '172.16.200.35', 'port': 6379},
    {'host': '172.16.200.36', 'port': 6379},
    {'host': '172.16.200.37', 'port': 6379},
    {'host': '172.16.200.38', 'port': 6379},
    {'host': '172.16.200.39', 'port': 6379},
    {'host': '172.16.200.40', 'port': 6379}
]

# init
rdc = RedisClusterClient(nodes)

if __name__ == '__main__':
    print(rdc.get_cop_show_num_dict('20358'))

    # rdc.get_cop_num('20358')
    # rdc.get_last_call_info('LastCallInfo:02023398853:13724059427')
    # print("none city:"+rdc.get_cop_num('20358'))
    s1 = rdc.get_cop_num('20358', '2')
    # UTF-8 --> decode 解码 --> Unicode
    # Unicode --> encode 编码 --> GBK / UTF-8
    print("with city: %s" % s1)
    print("with city: %s" % type(s1))
    # a = 20358
    # b = 1
    # rdc.get_cop_num('20358')
    # rdc.get_last_call_info('LastCallInfo:02023398853:13724059427')